package com.tanhua.server.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.nacos.client.utils.StringUtils;
import com.tanhua.common.utils.UserThreadLocal;
import com.tanhua.common.vo.ErrorResult;
import com.tanhua.dubbo.api.*;
import com.tanhua.dubbo.enums.SexEnum;
import com.tanhua.dubbo.pojo.*;
import com.tanhua.dubbo.vo.PageInfo;
import com.tanhua.server.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class MyCenterService {

    @DubboReference(version = "1.0.0")
    private UserInfoApi userInfoApi;

    @DubboReference(version = "1.0.0")
    private UserLikeApi userLikeApi;

    @DubboReference(version = "1.0.0")
    private QuestionApi questionApi;

    @DubboReference(version = "1.0.0")
    private SettingsApi settingsApi;

    @DubboReference(version = "1.0.0")
    private UserApi userApi;

    @DubboReference(version = "1.0.0")
    private BlacklistApi blacklistApi;


    @DubboReference(version = "1.0.0")
    private VisitorsApi visitorsApi;

    @DubboReference(version = "1.0.0")
    private RecommendUserApi recommendUserApi;

    @Autowired
    private IMService imService;

    @Autowired
    private TanHuaService tanHuaService;


    public UserInfoVo queryUserInfoByUserId(Long userId) {
        if (null == userId) {
            userId = UserThreadLocal.get();
        }

        //根据用户id查询用户信息
        UserInfo userInfo = this.userInfoApi.queryByUserId(userId);

        //封装UserInfoVo
        UserInfoVo userInfoVo = BeanUtil.toBeanIgnoreError(userInfo, UserInfoVo.class);
        userInfoVo.setGender(userInfo.getSex().name().toLowerCase());
        userInfoVo.setMarriage(StrUtil.equals("已婚", userInfo.getMarriage()) ? 1 : 0);
        return userInfoVo;
    }

    public Boolean isLike(Long userId) {
        return this.userLikeApi.isLike(UserThreadLocal.get(), userId);
    }


    public ErrorResult saveQuestions(String content) {
        Long userId = UserThreadLocal.get();
        Boolean result=  this.questionApi.saveQuestions(userId,content);

      //判断插入是否为空
        if(!result){
            return ErrorResult.builder().errCode("500").errMessage("服务器故障，暂时保存不了您的问题").build();
        }
        return null;
    }

    public Object querySettings() {
        Long userId = UserThreadLocal.get();

        SettingsVo settingsVo = new SettingsVo();
        settingsVo.setUserId(userId);//1

        //查询用户手机号
        User user = this.userApi.queryById(userId);
        if(ObjectUtil.isEmpty(user)){
            return ErrorResult.builder().errCode("500").errMessage("用户手机号不存在").build();
        }

        //用户信息存在,封装手机号
        settingsVo.setPhone(user.getMobile());//2

        //查询是否允许通知
        List<Settings> settings = this.settingsApi.querySettings(userId);
        //判断是不是只有一条设置
        if(settings.size()>1){
            return ErrorResult.builder().errCode("501").errMessage("设置重复").build();
        }
        //判断查到设置,赋值
        if(settings.size()>0){
            Settings setting = settings.get(0);
            //通知数据不为空，封装数据
            settingsVo.setGonggaoNotification(setting.getGonggaoNotification());//3
            settingsVo.setLikeNotification(setting.getLikeNotification());//4
            settingsVo.setPinglunNotification(setting.getPinglunNotification());//5
        }else{
            //通知为空，默认关闭
            settingsVo.setPinglunNotification(false);
            settingsVo.setLikeNotification(false);
            settingsVo.setGonggaoNotification(false);
        }

        //查询陌生人问题
        List<Question> questionList = this.questionApi.queryQuestion(userId);
        //判断查询的集合是否为空
        if(questionList.size()==0){
            //为空，返回未设置用户问题的信息
            return ErrorResult.builder().errCode("402").errMessage("您还未设置陌生人问题哦").build();
        }
        //不为空，获取问题
        if(questionList.size()>1){
            //查询到多条问题
            return  ErrorResult.builder().errCode("501").errMessage("查询到多条用户信息").build();
        }
        //查询到一条用户信息
        Question question = questionList.get(0);

        //陌生人问题不为空，封装陌生人问题
        settingsVo.setStrangerQuestion(question.getTxt());//6

        return settingsVo;
    }


    public ErrorResult setting(Boolean likeNotification, Boolean pinglunNotification, Boolean gonggaoNotification) {
        Long userId = UserThreadLocal.get();

        Boolean result= this.settingsApi.setting(likeNotification,pinglunNotification,gonggaoNotification,userId)==1;
        if(!result){
            return ErrorResult.builder().errCode("502").errMessage("设置通知失败").build();
        }
       return null;
    }

    public Object blacklist(Integer page, Integer pageSize) {
        Long userId = UserThreadLocal.get();

        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPagesize(pageSize);
        List<BlackListVo> blackVoList = new ArrayList<>();

        //查询黑名单用户id,根据时间降序排列
        PageInfo pageInfo=this.blacklistApi.queryBlacklist(page,pageSize,userId);
        List blackList = pageInfo.getRecords();
        //判断黑名单用户列表是否为空
        if(CollUtil.isEmpty(blackList)){
           return pageResult;
        }
        List<Object> blackUserId = CollUtil.getFieldValues(blackList, "blackUserId");
        //根据用户id,查询黑名单用户信息

        Map userInfoMap = this.userInfoApi.queryMapByUserIdList(blackUserId);

        //遍历按照更新时间降序排列
        for (Object blackUser : blackUserId) {
            UserInfo userInfo = (UserInfo) userInfoMap.get(Convert.toLong(blackUser));
            BlackListVo blackListVo = BeanUtil.toBeanIgnoreError(userInfo, BlackListVo.class);
            blackListVo.setGender(userInfo.getSex().name().toLowerCase());
            blackVoList.add(blackListVo);
        }
        pageResult.setItems(blackVoList);
        return pageResult;
    }

    public Object deleteBlacklist(Long uid) {
        Long userId = UserThreadLocal.get();
        Boolean result= this.blacklistApi.deleteBlackList(uid,userId);
        if(!result){
            return  ErrorResult.builder().errCode("401").errMessage("黑名单用户不存在").build();
        }
        return  this.blacklist(1, 10);
    }



    public CountsVo queryCounts() {
        Long userId = UserThreadLocal.get();
        CountsVo countsVo = new CountsVo();
        countsVo.setFanCount(this.userLikeApi.queryFanCount(userId));
        countsVo.setLoveCount(this.userLikeApi.queryLikeCount(userId));
        countsVo.setEachLoveCount(this.userLikeApi.queryMutualLikeCount(userId));
        return countsVo;
    }

    public PageResult queryLikeList(Integer type, Integer page, Integer pageSize, String nickname) {
        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPagesize(pageSize);

        Long userId = UserThreadLocal.get();

        List<Object> userIdList = null;

        //1 互相关注 2 我关注 3 粉丝 4 谁看过我
        switch (type) {
            case 1: {
                PageInfo<UserLike> pageInfo = this.userLikeApi.queryMutualLikeList(userId, page, pageSize);
                userIdList = CollUtil.getFieldValues(pageInfo.getRecords(), "userId");
                break;
            }
            case 2: {
                PageInfo<UserLike> pageInfo = this.userLikeApi.queryLikeList(userId, page, pageSize);
                userIdList = CollUtil.getFieldValues(pageInfo.getRecords(), "likeUserId");
                break;
            }
            case 3: {
                PageInfo<UserLike> pageInfo = this.userLikeApi.queryFanList(userId, page, pageSize);
                userIdList = CollUtil.getFieldValues(pageInfo.getRecords(), "userId");
                break;
            }
            case 4: {
                PageInfo<Visitors> pageInfo = this.visitorsApi.topVisitor(userId, page, pageSize);
                userIdList = CollUtil.getFieldValues(pageInfo.getRecords(), "visitorUserId");
                break;
            }
            default:
                return pageResult;
        }

        if (CollUtil.isEmpty(userIdList)) {
            return pageResult;
        }

        Map<Long, UserInfo> userInfoMap = this.userInfoApi.queryMapByUserIdList(userIdList);
        List<UserLikeListVo> userLikeListVos = new ArrayList<>();
        for (Object uid  : userIdList) {
            UserLikeListVo userLikeListVo = new UserLikeListVo();
            UserInfo userInfo = userInfoMap.get(uid);
            userLikeListVo.setAge(userInfo.getAge());
            userLikeListVo.setAvatar(userInfo.getLogo());
            userLikeListVo.setCity(userInfo.getCity());
            userLikeListVo.setEducation(userInfo.getEdu());
            userLikeListVo.setGender(userInfo.getSex().name().toLowerCase());
            userLikeListVo.setId(userInfo.getUserId());
            userLikeListVo.setMarriage(StringUtils.equals(userInfo.getMarriage(), "已婚") ? 1 : 0);
            userLikeListVo.setNickname(userInfo.getNickName());
            //是否喜欢  userLikeApi中的isLike开放出来
            userLikeListVo.setAlreadyLove(this.userLikeApi.isLike(userId, userInfo.getUserId()));


            Double score = this.recommendUserApi.queryScore(userId, userInfo.getUserId());
            userLikeListVo.setMatchRate(Convert.toInt(score));

            userLikeListVos.add(userLikeListVo);
        }

        pageResult.setItems(userLikeListVos);

        return pageResult;
    }


    /**
     * 取消喜欢
     *
     * @param uid
     */
    public void disLike(Long uid) {
        //判断当前用户与此用户是否相互喜欢
        Long userId = UserThreadLocal.get();
        Boolean mutualLike = this.userLikeApi.isMutualLike(userId, uid);
        this.userLikeApi.notLikeUser(userId, uid);
        if (mutualLike) {
            //取消喜欢
            this.imService.removeUser(userId);
        }
        //取消好友关系，解除在环信平台的好友关系
    }


    /**
     * 喜欢
     *
     * @param userId
     */
    public void likeFan(Long userId) {
        //喜欢用户，如果用户是相互喜欢的话就会成为好友
        this.tanHuaService.likeUser(userId);
    }

    /**
     * 更新用户信息
     *
     * @param userInfoVo
     * @return
     */
    public Boolean updateUserInfo(UserInfoVo userInfoVo) {
        Long userId = UserThreadLocal.get();
        UserInfo userInfo = new UserInfo();
        userInfo.setUserId(userId);
        userInfo.setAge(Integer.valueOf(userInfoVo.getAge()));
        userInfo.setSex(StrUtil.equalsIgnoreCase(userInfoVo.getGender(), "man") ? SexEnum.MAN : SexEnum.WOMAN);
        userInfo.setBirthday(userInfoVo.getBirthday());
        userInfo.setCity(userInfoVo.getCity());
        userInfo.setEdu(userInfoVo.getEducation());
        userInfo.setIncome(StrUtil.replace(userInfoVo.getIncome(), "K", ""));
        userInfo.setIndustry(userInfoVo.getProfession());
        userInfo.setMarriage(userInfoVo.getMarriage() == 1 ? "已婚" : "未婚");
        return this.userInfoApi.update(userInfo);
    }
}
